package com.hsy.linemoney.modules.exchange;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.deparse.dpframe.tools.utils.DPGsonUtil;
import com.deparse.dpframe.tools.utils.DPLogUtil;
import com.deparse.dpframe.ui.common.DPBusEvent;
import com.hsy.linemoney.R;
import com.hsy.linemoney.apiservice.AccountService;
import com.hsy.linemoney.apiservice.BusinessService;
import com.hsy.linemoney.apiservice.CalculateService;
import com.hsy.linemoney.apiservice.Callback;
import com.hsy.linemoney.apiservice.LineMoneyContext;
import com.hsy.linemoney.apiservice.ParamsMaker;
import com.hsy.linemoney.common.Consts;
import com.hsy.linemoney.modules.account.CreateReceiveAccountActivity;
import com.hsy.linemoney.modules.common.CommonBaseActivityWithSimpleActionBar;
import com.hsy.linemoney.modules.common.EditTextExt;
import com.hsy.linemoney.modules.common.ProcessPayActivity;
import com.hsy.linemoney.modules.common.StepView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class ExchangeStep3Activity extends CommonBaseActivityWithSimpleActionBar implements View.OnClickListener {

    protected StepView stepView;
    protected View indicator0;
    protected RelativeLayout recordsExists;
    protected TextView nextStep;
    protected ViewGroup contentDisplayArea;

    private AccountService.AccountListResult mAccountListResult;
    private int selectedAccountWhich = -1;

    private List<AccountService.AccountListResult.Value> receiveAccounts = new ArrayList<>();

    @Override
    public int getRightbuttonIconResId() {
        return R.mipmap.ic_exchange_add_receiver;
    }

    @Override
    public boolean onActionBarRightButtonClicked(ImageButton rightButton) {
        ExchangeOnceOrderParamsData data = DPGsonUtil.fromJson(getActivityStartExtra()[0], ExchangeOnceOrderParamsData.class);
        startActivity(CreateReceiveAccountActivity.class, "RECEIVE", "", data.getToCurrencyCd());
        return true;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_exchange_step3);
        setTitle(R.string.txt_rec_account);
        initView();
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.next_step) {
            if (checkThrought()) {
                final ExchangeOnceOrderParamsData data = DPGsonUtil.fromJson(getActivityStartExtra()[0], ExchangeOnceOrderParamsData.class);
                data.setToAccountId(receiveAccounts.get(selectedAccountWhich).getAccountId());
                final CalculateService.CalculateResult calculateResult = DPGsonUtil.fromJson(getActivityStartExtra()[1], CalculateService.CalculateResult.class);
                final ExchangeConfirmDialog.ExchangeConfirmDialogData dialogData = new ExchangeConfirmDialog.ExchangeConfirmDialogData();
                dialogData.setCosts(calculateResult.getData().getLmData().getLinemoneyTransferFee());
                dialogData.setCostsUnit(data.getFromCurrencyCdUnit());
                dialogData.setExchangeAmount(data.getFromAmount());
                dialogData.setExchangeAmountUnity(data.getFromCurrencyCdUnit());
                dialogData.setExchangeRate(calculateResult.getData().getLmData().getLinemoneyRate());
                dialogData.setFromAccountId(data.getFromAccountId());
                dialogData.setToAccountId(data.getToAccountId());

                double rate = Double.valueOf(calculateResult.getData().getLmData().getLinemoneyRate());
                double from = Double.valueOf(data.getFromAmount());
                double fee = Double.valueOf(calculateResult.getData().getLmData().getLinemoneyTransferFee());
                dialogData.setMoneyTheOtherSideReceived(String.format(LineMoneyContext.getLocalCountryPair().locale, "%.02f", rate * from - fee));

                dialogData.setMoneyTheOtherSideReceivedUnit(data.getToCurrencyCdUnit());

                new ExchangeConfirmDialog(this, dialogData, new ExchangeConfirmDialog.OnCommitListener() {
                    @Override
                    public void onCommit(String pass) {
                        showProgressDialog(ExchangeStep3Activity.this);
                        AccountService accountService = new AccountService();
                        accountService.checkAccountPassword(pass, new Callback<JSONObject>() {

                            @Override
                            public void onSuccess(int what, JSONObject result) {
                                try {
                                    if (null != result && result.has("value") && "PASSWORD_MATCHED".equalsIgnoreCase(result.getString("value"))) {
                                        data.setToAccountId(receiveAccounts.get(selectedAccountWhich).getAccountId());
                                        data.setUserId(LineMoneyContext.getLoggedUser().getUserId());

                                        BusinessService service = new BusinessService();
                                        JSONObject params;
                                        if ("0".equals(data.getFxRate())) {
                                            params = ParamsMaker.newInstance()
                                                    .add("userId", data.getUserId())
                                                    .add("parentOrderId", "-1")
                                                    .add("fromCurrencyCd", data.getFromCurrencyCd())
                                                    .add("toCurrencyCd", data.getToCurrencyCd())
                                                    .add("fromAccountId", data.getFromAccountId())
                                                    .add("toAccountId", data.getToAccountId())
                                                    .add("fromAmount", data.getFromAmount())
                                                    .add("serviceTypeCd", data.getServiceTypeCd())
                                                    .add("recurringTypeCd", "")
                                                    .add("durationTypeCd", "")
                                                    .add("fxRate", calculateResult.getData().getLmData().getLinemoneyRate())
                                                    .get();
                                        } else {
                                            params = ParamsMaker.newInstance()
                                                    .add("userId", data.getUserId())
                                                    .add("parentOrderId", "-1")
                                                    .add("fromCurrencyCd", data.getFromCurrencyCd())
                                                    .add("toCurrencyCd", data.getToCurrencyCd())
                                                    .add("fromAccountId", data.getFromAccountId())
                                                    .add("toAccountId", data.getToAccountId())
                                                    .add("fromAmount", data.getFromAmount())
                                                    .add("serviceTypeCd", data.getServiceTypeCd())
                                                    .add("recurringTypeCd", "")
                                                    .add("durationTypeCd", "")
                                                    .add("fxRate", data.getFxRate())
                                                    .get();
                                        }

                                        DPLogUtil.d("fxRate=" + params.optString("fxRate"));
                                        service.createOrder(params, new Callback<BusinessService.OrderCreateResult>() {
                                            @Override
                                            public void onSuccess(int what, BusinessService.OrderCreateResult result) {
                                                hideProgressDialog();
                                                if (null != result.getStatus() && "200".equals(result.getStatus().getCode())) {
//                                                    startActivity(ProcessPayActivity.class, result.getValue().getToLmBankAccountIdString(), "0");
                                                    startActivity(ExchangeFinishActivity.class, result.getValue().getOrderId(), result.getValue().getToLmBankAccountIdString());
                                                } else {
                                                    if (null != result.getStatus() && null != result.getStatus().getMessage()) {
                                                        showToast(result.getStatus().getMessage());
                                                    } else {
                                                        showToast(R.string.txt_create_order_failed);
                                                    }
                                                }
                                            }

                                            @Override
                                            public void onError(int what, int type, String msg, Exception e) {
                                                hideProgressDialog();
                                            }
                                        });
                                    } else {
                                        hideProgressDialog();
                                        showToast(R.string.txt_account_pass_err);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    hideProgressDialog();
                                    showToast(R.string.txt_account_pass_err);
                                }
                            }

                            @Override
                            public void onError(int what, int type, String msg, Exception e) {
                                hideProgressDialog();
                                showToast(msg);
                            }
                        });
                    }
                }).show();
            }
        } else if (view.getId() == R.id.records_exists) {
            AccountService service = new AccountService();
            service.getAccounts(new Callback<AccountService.AccountListResult>() {
                @Override
                public void onSuccess(int what, final AccountService.AccountListResult result) {
                    ExchangeStep3Activity.this.mAccountListResult = result;
                    ExchangeOnceOrderParamsData data = DPGsonUtil.fromJson(getActivityStartExtra()[0], ExchangeOnceOrderParamsData.class);
                    receiveAccounts.clear();
                    receiveAccounts = new ArrayList<>();
                    for (AccountService.AccountListResult.Value v : result.getValue()) {
                        if ("RECEIVE".equalsIgnoreCase(v.getAccountTypeCd())/* && data.getToCurrencyCd().equalsIgnoreCase(v.getCurrencyCd())*/) {
                            receiveAccounts.add(v);
                        }
//                        accounts.add(v);
                    }
                    if (0 == receiveAccounts.size()) {
                        showToast(R.string.txt_no_existed_receive_accounts_please_add);
                    } else {
                        String[] accountNames = new String[receiveAccounts.size()];
                        for (int i = 0; i < receiveAccounts.size(); i++) {
                            accountNames[i] = receiveAccounts.get(i).getAccountName();
                        }
                        showListDialog(accountNames, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                selectedAccountWhich = which;
                                showScreen(receiveAccounts.get(which));
                            }
                        });
                    }
                }

                @Override
                public void onError(int what, int type, String msg, Exception e) {

                }
            });
        }
    }

    private boolean checkThrought() {
        return selectedAccountWhich >= 0;
    }

    private void showScreen(AccountService.AccountListResult.Value v) {
//        if ("bank".equalsIgnoreCase(v.getPaymentTypeCd())) {
//
//        } else if ("card".equalsIgnoreCase(v.getPaymentTypeCd())) {
//
//        } else if ("zhiFuBao".equalsIgnoreCase(v.getPaymentTypeCd())) {
        contentDisplayArea.removeAllViewsInLayout();
        View view = LayoutInflater.from(this).inflate(R.layout.activity_exchange_step3_zhifubao, null);
        contentDisplayArea.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        EditTextExt receiverName;
        EditTextExt tel;
        EditTextExt email;

        receiverName = (EditTextExt) view.findViewById(R.id.receiver_name);
        tel = (EditTextExt) view.findViewById(R.id.tel);
        email = (EditTextExt) view.findViewById(R.id.email);

        receiverName.setText(v.getFirstName() + " " + v.getLastName());
        tel.setText(v.getPhone());
        email.setText(v.getEmail());
//        } else if ("paypal".equalsIgnoreCase(v.getPaymentTypeCd())) {
//            contentDisplayArea.removeAllViewsInLayout();
//            View view = LayoutInflater.from(this).inflate(R.layout.activity_exchange_step3_paypal, null);
//            contentDisplayArea.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//            ((EditText) view.findViewById(R.id.account)).setText(v.getAccountName());
//        }
    }

    private void initView() {
        stepView = (StepView) findViewById(R.id.step_view);
        indicator0 = (View) findViewById(R.id.indicator_0);
        recordsExists = (RelativeLayout) findViewById(R.id.records_exists);
        recordsExists.setOnClickListener(this);
        contentDisplayArea = F(R.id.content_display_area);
        nextStep = (TextView) findViewById(R.id.next_step);
        nextStep.setOnClickListener(ExchangeStep3Activity.this);

        stepView.setCurrentStep(3);
    }

    @Override
    public void onEventMainThread(DPBusEvent event) {
        super.onEventMainThread(event);
        if (event.what == Consts.BusEventCommands.FINISH_EXCHANGE_STEP_2_AND_3) {
            finish();
        }
    }

    private void showListDialog(String[] items, DialogInterface.OnClickListener listener) {
        new AlertDialog.Builder(this).setItems(items, listener).show();
    }
}
